import requests
import hashlib
import time


class TaoBao(object):

    def __init__(self, app_key, secret, method, host_url="http://gw.api.taobao.com/router/rest", sign_method="md5"):
        self.host_url = host_url
        self.app_key = app_key
        self.sign_method = sign_method
        self.secret = secret
        self.method = method

    def get_params(self):
        return {
            "format": "json",
            "app_key": self.app_key,
            "sign_method": self.sign_method,
            "v": "2.0",
            "timestamp": str(int(time.time() * 1000)),
            "method": self.method
        }

    @staticmethod
    def sign(secret, parameters):
        # ===========================================================================
        '''签名方法
        @param secret: 签名需要的密钥
        @param parameters: 支持字典和string两种
        # '''
        # ===========================================================================
        # 如果parameters 是字典类的话
        if hasattr( parameters, "items" ):
            keys = parameters.keys()
            # keys.sort()
            keys = sorted( keys )
            parameters = "%s%s%s" % (secret,
                                     str().join( '%s%s' % (key, parameters[key]) for key in keys ),
                                     secret)
        sign = hashlib.md5( parameters.encode() ).hexdigest().upper()
        return sign

    def getApplicationParameters(self):
        application_parameter = {}
        for key, value in self.__dict__.items():
            if not key.startswith( "__" ) and not key in self.getMultipartParas() and not key.startswith(
                    "_RestApi__" ) and value is not None:
                if (key.startswith( "_" )):
                    application_parameter[key[1:]] = value
                else:
                    application_parameter[key] = value
        # 查询翻译字典来规避一些关键字属性
        translate_parameter = self.getTranslateParas()
        for key, value in application_parameter.items():
            if key in translate_parameter:
                application_parameter[translate_parameter[key]] = application_parameter[key]
                del application_parameter[key]
        return application_parameter

    def getMultipartParas(self):
        return []

    def getTranslateParas(self):
        return {}

    def run(self):
        params = self.get_params()
        temp = params.copy()
        app = self.getApplicationParameters()
        temp.update(app)
        __sign = self.sign(self.secret, temp)
        params["sign"] = __sign
        res = requests.post(self.host_url, data=app, params=params)
        print( res.status_code )
        print( res.text )

        return res


if __name__ == '__main__':

    app_key = "22222222"
    secret = "assssasdfdfsad3"
    method = "taobao.tbk.uatm.favorites.get"
    taobao = TaoBao(app_key, secret, method)
    taobao.num_iids = "580227407296"
    taobao.run()
